package com.nova.bluetooth.ui.device;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.dido.fastblelib.utils.HexUtil;
import com.nova.bluetooth.MyApp;
import com.nova.bluetooth.R;
import com.nova.bluetooth.base.BaseFragment;
import com.nova.bluetooth.base.DeviceMessageWrap;
import com.nova.bluetooth.databinding.FragmentDeviceTabBinding;
import com.nova.bluetooth.helpUtils.AppUtil;
import com.nova.bluetooth.helpUtils.BluetoothDataUtil;
import com.nova.bluetooth.helpUtils.EventBusUtil;
import com.nova.bluetooth.helpUtils.LogUtil;
import com.nova.bluetooth.helpUtils.OnClickEvent;
import com.nova.bluetooth.helpUtils.ToastUtils;
import com.nova.bluetooth.manage.BluetoothHelper;
import com.nova.bluetooth.myEnum.DenoiseMode;
import com.nova.bluetooth.myEnum.DenoiseModeLevel;
import com.nova.bluetooth.myEnum.ImmersionModel;
import com.nova.bluetooth.ui.ai.aiNote.AudioFileToTextActivity;
import com.nova.bluetooth.ui.ai.aiNote.VoiceToTextActivity;
import com.nova.bluetooth.ui.ai.translate.AudioTranslatingActivity;
import com.nova.bluetooth.ui.bluetoothDemo.MainActivity;
import com.nova.bluetooth.ui.bluetoothDemo.NovaBluetoothControlViewModel;
import com.nova.bluetooth.widget.CommonDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.nio.charset.StandardCharsets;

/**
 *
 */
public class DeviceTabFragment extends BaseFragment {
    private FragmentDeviceTabBinding binding;
    private NovaBluetoothControlViewModel deviceViewModel;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(DeviceMessageWrap message) {
        switch (message.getEventCode()) {
            case DeviceMessageWrap.ACTION_DEVICE_CONNECTED:
                checkConnectedDevice();
                break;
            case DeviceMessageWrap.ACTION_DEVICE_DISCONNECTED:
                break;
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        EventBusUtil.register(this);
        View view = inflater.inflate(R.layout.fragment_device_tab, container, false);
        deviceViewModel = new ViewModelProvider(MyApp.getInstance()).get(NovaBluetoothControlViewModel.class);
        binding = FragmentDeviceTabBinding.bind(view);
        binding.setOnClick(onClickEvent);
        binding.setVm(deviceViewModel);
        binding.setLifecycleOwner(this);
        initView();
        observe();
        return binding.getRoot();
    }

    private void initView() {
        binding.llManagerDevice.setOnClickListener(onClickEvent);
        binding.tvToScanDevice.setOnClickListener(onClickEvent);
        binding.tvManagerConnected.setOnClickListener(onClickEvent);
        binding.layoutAudioTranslate.setOnClickListener(onClickEvent);
        binding.layoutAudioFileTurn.setOnClickListener(onClickEvent);
        binding.layoutAudioTurn.setOnClickListener(onClickEvent);
        binding.ivDevicePic.setOnClickListener(onClickEvent);

        binding.includeFindDevice.ivFuncitonIc.setImageResource(R.drawable.ic_devive_find);
        binding.includeFindDevice.tvTitle.setText("查找耳机");
        binding.includeFindDevice.getRoot().setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                DeviceContainerActivity.startThisActivity(getActivity(),
                        DeviceContainerActivity.FRAGMENT_TAG_FIND_DEVICE);
            }
        });

        binding.includeEq.ivFuncitonIc.setImageResource(R.drawable.ic_devive_eq);
        binding.includeEq.tvTitle.setText("EQ设置");
        binding.includeEq.getRoot().setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                DeviceContainerActivity.startThisActivity(getActivity(),
                        DeviceContainerActivity.FRAGMENT_TAG_EQ_SETTING);
            }
        });

        binding.includeGame.ivFuncitonIc.setImageResource(R.drawable.ic_devive_game);
        binding.includeGame.tvTitle.setText("游戏模式");
        binding.includeGame.ivSwitch.setVisibility(VISIBLE);
        binding.includeGame.ivGo.setVisibility(GONE);
        binding.includeGame.ivSwitch.setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                boolean isSelected = binding.includeGame.ivSwitch.isSelected();
                BluetoothHelper.getInstance().sendByteArrayDataSafety(
                        BluetoothDataUtil.getGameModelSetCMD(!isSelected));
                binding.includeGame.ivSwitch.setSelected(!isSelected);
            }
        });


        binding.includeRename.ivFuncitonIc.setImageResource(R.drawable.ic_devive_rename);
        binding.includeRename.tvTitle.setText("设备名修改");
        binding.includeRename.getRoot().setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                showRenameDialog();
                String name = "D20";
                byte[] cityByte = name.getBytes(StandardCharsets.UTF_8);
                LogUtil.d("test==>D20:" + HexUtil.encodeHexStr(cityByte));
            }
        });

        binding.includeKeyFunction.ivFuncitonIc.setImageResource(R.drawable.ic_devive_key_function);
        binding.includeKeyFunction.tvTitle.setText("耳机操控");
        binding.includeKeyFunction.getRoot().setOnClickListener(new OnClickEvent() {
            @Override
            public void singleClick(View v) {
                DeviceContainerActivity.startThisActivity(getActivity(),
                        DeviceContainerActivity.FRAGMENT_TAG_KEY_FUNCTION);
            }
        });
    }


    private void observe() {
        deviceViewModel.immersionModelMutableLiveData.observe(getViewLifecycleOwner(), immersionModelMutableLiveData -> {
            immersionModel = immersionModelMutableLiveData;
            changeImmersionSoundView();
        });
        deviceViewModel.denoiseMutableLiveData.observe(getViewLifecycleOwner(), denoiseModeDenoiseModeLevelPair -> {
            denoiseMode = denoiseModeDenoiseModeLevelPair.getFirst();
            denoiseModeLevel = denoiseModeDenoiseModeLevelPair.getSecond();
            changeDenoiseView();
        });

        deviceViewModel.isGameModelOpenLiveData.observe(getViewLifecycleOwner(), isGameModelOpenLiveData -> {
            binding.includeGame.ivSwitch.setSelected(isGameModelOpenLiveData);
        });
    }

    @Override
    public void onResume() {
        super.onResume();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBusUtil.unRegister(this);
    }

    private void checkConnectedDevice() {
        if (BluetoothHelper.getInstance().isConnected()) {
            binding.tvDeviceName.setText(BluetoothHelper.getmConnectedBleDevice().getName());
        }
    }


    private void showRenameDialog() {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_change_device_name, null);
        CommonDialog renameDialog = new CommonDialog(getActivity(), dialogView);

        TextView tvAgree = dialogView.findViewById(R.id.tv_confirm);
        EditText input = dialogView.findViewById(R.id.et_input);
        tvAgree.setOnClickListener(v -> {
            AppUtil.hideKeyboard(binding.getRoot());
            String resetName = input.getText().toString();
            if (!TextUtils.isEmpty(resetName)) {
                BluetoothHelper.getInstance().sendByteArrayDataSafety(
                        BluetoothDataUtil.getReNameCMD(resetName));
            } else {
                ToastUtils.show("输入为空");
            }
            renameDialog.dismissDialog();
        });

        TextView tvDisagree = dialogView.findViewById(R.id.tv_cance);
        tvDisagree.setOnClickListener(v -> {
            renameDialog.dismissDialog();
        });

        renameDialog.setWidth(R.dimen.dp_320);
        renameDialog.setCancelable(false);
        renameDialog.setGravity(Gravity.CENTER);
        renameDialog.showDialog();
    }

    private ImmersionModel immersionModel = ImmersionModel.Off;

    private void changeImmersionSoundView() {
        binding.layoutSpace1.setSelected(false);
        binding.layoutSpace2.setSelected(false);
        binding.layoutSpace3.setSelected(false);
        binding.tvSpace1.setSelected(false);
        binding.tvSpace2.setSelected(false);
        binding.tvSpace3.setSelected(false);
        switch (immersionModel) {
            case Off:
                binding.layoutSpace2.setSelected(true);
                binding.tvSpace2.setSelected(true);
                break;
            case Statical:
                binding.layoutSpace1.setSelected(true);
                binding.tvSpace1.setSelected(true);
                break;
            case Dynamic:
                binding.layoutSpace3.setSelected(true);
                binding.tvSpace3.setSelected(true);
                break;
        }
    }

    private void sendImmersionSoundCMD(View view) {
        if (view.getId() == R.id.layout_space_2) {
            immersionModel = ImmersionModel.Off;
        } else if (view.getId() == R.id.layout_space_1) {
            immersionModel = ImmersionModel.Statical;
        } else if (view.getId() == R.id.layout_space_3) {
            immersionModel = ImmersionModel.Dynamic;
        }

        BluetoothHelper.getInstance().sendByteArrayDataSafety(
                BluetoothDataUtil.getImmersionModelSetCMD(immersionModel));
    }


    private DenoiseMode denoiseMode = DenoiseMode.NOISE_MODE_DENOISE;
    private DenoiseModeLevel denoiseModeLevel = DenoiseModeLevel.NOISE_MODE_LEVEL_MILD;

    private void changeDenoiseView() {
        binding.layoutNoise1.setSelected(false);
        binding.layoutNoise2.setSelected(false);
        binding.layoutNoise3.setSelected(false);
        binding.tvNoise1.setSelected(false);
        binding.tvNoise2.setSelected(false);
        binding.tvNoise3.setSelected(false);

        switch (denoiseMode) {
            case NOISE_MODE_DENOISE:
                binding.layoutNoise1.setSelected(true);
                binding.tvNoise1.setSelected(true);
                break;
            case NOISE_MODE_TRANSPARENT:
                binding.layoutNoise3.setSelected(true);
                binding.tvNoise3.setSelected(true);
                break;
            case NOISE_MODE_OFF:
                binding.layoutNoise2.setSelected(true);
                binding.tvNoise2.setSelected(true);
                break;
        }

//        switch (denoiseModeLevel) {
//            case NOISE_MODE_LEVEL_MILD:
//                binding.includeDenoiseSet.levelRadioButton1.setChecked(true);
//                break;
//            case NOISE_MODE_LEVEL_MEDIUM:
//                binding.includeDenoiseSet.levelRadioButton2.setChecked(true);
//                break;
//            case NOISE_MODE_LEVEL_SEVERE:
//                binding.includeDenoiseSet.levelRadioButton3.setChecked(true);
//                break;
//            case NOISE_MODE_LEVEL_NULL:
//                break;
//        }
    }

    private void sendDenoiseCMD(View view) {
        if (view.getId() == R.id.layout_noise_1) {
            denoiseMode = DenoiseMode.NOISE_MODE_DENOISE;
        } else if (view.getId() == R.id.layout_noise_3) {
            denoiseMode = DenoiseMode.NOISE_MODE_TRANSPARENT;
        } else if (view.getId() == R.id.layout_noise_2) {
            denoiseMode = DenoiseMode.NOISE_MODE_OFF;
        }

//        else if (radioButton.getId() == R.id.level_radio_button_1) {
//            denoiseModeLevel = DenoiseModeLevel.NOISE_MODE_LEVEL_MILD;
//        } else if (radioButton.getId() == R.id.level_radio_button_2) {
//            denoiseModeLevel = DenoiseModeLevel.NOISE_MODE_LEVEL_MEDIUM;
//        } else if (radioButton.getId() == R.id.level_radio_button_3) {
//            denoiseModeLevel = DenoiseModeLevel.NOISE_MODE_LEVEL_SEVERE;
//        }

        byte[] setCMD = BluetoothDataUtil.getDenoiseSetCMD(denoiseMode, denoiseModeLevel);
        BluetoothHelper.getInstance().sendByteArrayDataSafety(setCMD);
    }

    private final OnClickEvent onClickEvent = new OnClickEvent() {
        @Override
        public void singleClick(View v) {
            if (v.getId() == R.id.ll_manager_device) {
                startActivity(new Intent(getActivity(), MainActivity.class));
            } else if (v.getId() == R.id.tv_to_scan_device) {
                startActivity(new Intent(getActivity(), AppScanBluetoothActivity.class));
            } else if (v.getId() == R.id.tv_manager_connected) {
//                startActivity(new Intent(getActivity(), ConnectedListActivity.class));
            } else if (v.getId() == R.id.layout_audio_translate) {
                startActivity(new Intent(getActivity(), AudioTranslatingActivity.class));
            } else if (v.getId() == R.id.layout_audio_file_turn) {
                startActivity(new Intent(getActivity(), AudioFileToTextActivity.class));
            } else if (v.getId() == R.id.layout_audio_turn) {
                startActivity(new Intent(getActivity(), VoiceToTextActivity.class));
            } else if (v.getId() == R.id.iv_device_pic) {
//                boolean isConnected = deviceViewModel.isConnectedLiveData.getValue();
//                deviceViewModel.isConnectedLiveData.setValue(!isConnected);
            } else if (v.getId() == R.id.layout_space_1 ||
                    v.getId() == R.id.layout_space_2 ||
                    v.getId() == R.id.layout_space_3) {
                sendImmersionSoundCMD(v);
                changeImmersionSoundView();
            } else if (v.getId() == R.id.layout_noise_1 ||
                    v.getId() == R.id.layout_noise_2 ||
                    v.getId() == R.id.layout_noise_3) {
                sendDenoiseCMD(v);
                changeDenoiseView();
            }
        }
    };
}
